package com.example.demo.core.resolver;


import com.example.demo.core.annotations.DefaultValue;
import com.example.demo.core.exception.ProgramException;
import com.example.demo.core.util.JacksonUtil;
import com.example.demo.core.util.RegexUtil;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Parameter;
import java.util.Optional;


/**
 * @author yj
 * @date 2021-05-12 12:00
 */
@Component
public class DefaultValueResolver implements HandlerMethodArgumentResolver {

    private Logger logger = LoggerFactory.getLogger(DefaultValueResolver.class);

    @Override
    public boolean supportsParameter(@NotNull MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(DefaultValue.class);
    }

    @Override
    public Object resolveArgument(@NotNull MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  @NotNull NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        DefaultValue defaultValue = Optional
                .ofNullable(methodParameter.getParameterAnnotation(DefaultValue.class))
                .orElseThrow(() -> new ProgramException("参数异常"));
        HttpServletRequest httpServletRequest = Optional
                .ofNullable(nativeWebRequest.getNativeRequest(HttpServletRequest.class))
                .orElseThrow(() -> new ProgramException("参数异常"));
        String parameter = httpServletRequest.getParameter(methodParameter.getParameter().getName());
        if (RegexUtil.checkObjectIsNull(parameter)) {
            return JacksonUtil.jsonToClassEntity(defaultValue.value(), methodParameter.getParameterType());
        }
        return JacksonUtil.jsonToClassEntity(parameter, methodParameter.getParameterType());
    }
}